<template>
	<div class="">
		<ProTable ref="proTable" title="广告管理" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'advertisement:create:invoke'" @click="toUpdate()"> 新增广告 </el-button>
				</div>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<template #tableHeader>
				<el-tabs v-model="activeTag" class="demo-tabs" @tab-click="handleTab">
					<el-tab-pane v-for="item in tags" :key="item.name" :label="`${item.label}(${item.data})`" :name="item.name"></el-tab-pane>
				</el-tabs>
			</template>
			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button
					type="primary"
					link
					v-auth-all="['advertisement:management:sub:details:invoke', 'advertisement:edit:invoke']"
					@click="toUpdate(row)"
				>
					编辑
				</el-button>
				<el-divider direction="vertical" v-auth-all="['advertisement:management:sub:details:invoke', 'advertisement:edit:invoke']" />
				<el-button type="primary" link v-auth="'advertisement:management:sub:delete:invoke'" @click="delAdvertisement(row)"> 删除 </el-button>
			</template>
		</ProTable>
	</div>
</template>

<script setup lang="tsx" name="advertisementList">
import { computed, inject, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../components/ProTable/interface';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { advertisementPage, advertisementDelete, advertisementCount } from '/@/api/advertisement';
const router = useRouter();
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ID',
	paramTimeType: 'register',
});
const activeTag = ref<any>('');
const tags = ref<any>([
	{
		label: '全部广告',
		name: '',
		data: 0,
	},
	{
		label: '待上线',
		name: 'PENDING',
		data: 0,
	},
	{
		label: '进行中',
		name: 'IN-PROGRESS',
		data: 0,
	},
	{
		label: '已下线',
		name: 'OFFLINE',
		data: 0,
	},
]);
const searchArr = [
	{
		label: '广告ID',
		value: 'ID',
	},
	{
		label: '广告名称',
		value: 'NAME',
	},
];
// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '广告搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => {
								scope.searchParam.searchType = value;
							}}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},

	{
		prop: 'paramTime',
		label: '时间筛选',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.paramTimeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.paramTimeType = value)}
						>
							{[
								{
									label: '投放时间',
									value: 'register',
								},
							].map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm"
							date-format="YYYY-MM-DD"
							time-format="HH:mm"
						/>
					</div>
				);
			},
		},
	},
	{
		prop: 'position',
		label: '广告位置',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '请选择广告位置', clearable: true, filterable: true } },
		enum: [
			{
				label: '首页轮播',
				value: 0,
			},
			{
				label: '首页图文导航',
				value: 1,
			},
			{
				label: '商城轮播',
				value: 2,
			},
			{
				label: '内容轮播',
				value: 3,
			},
			{
				label: '我的轮播',
				value: 4,
			},
		],
	},
	{
		prop: 'channel',
		label: '投放渠道',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '请选择投放渠道', clearable: true, filterable: true } },
		enum: [
			{
				label: '支付宝小程序',
				value: 1,
			},
			{
				label: '微信小程序',
				value: 2,
			},
		],
	},
	{
		prop: 'id',
		label: '广告ID',
		minWidth: 120,
	},
	{
		prop: 'image',
		label: '广告图片',
		minWidth: 120,
		render: (scope) => {
			return <el-image src={scope.row.image}></el-image>;
		},
	},
	{
		prop: 'title',
		label: '广告名称',
		minWidth: 120,
	},
	{
		prop: 'position',
		label: '广告位置',
		minWidth: 120,
		render: (scope) => {
			return scope.row.position;
		},
	},
	{
		prop: 'channel',
		label: '投放渠道',
		minWidth: 120,
		render: (scope) => {
			return scope.row.channel;
		},
	},
	{
		prop: 'type',
		label: '落地页方式',
		minWidth: 120,
	},
	{
		prop: 'time',
		label: '投放时间',
		minWidth: 120,
	},
	{
		prop: 'status',
		label: '广告状态',
		minWidth: 120,
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 150, align: 'left' },
];
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const handleParams = (params: any) => {
	let data = {
		...params,
		status: activeTag.value,
	};
	if (data.paramTime) {
		data.startTime = dayjs(data.paramTime[0]).format('YYYY-MM-DD HH:mm');
		data.endTime = dayjs(data.paramTime[1]).format('YYYY-MM-DD HH:mm');
		delete data.paramTimeType;
		delete data.paramTime;
	}
	delete data.paramTimeType;
	return data;
};
const getTableList = (params: any) => {
	const data = handleParams(params);
	getCount(data);
	return advertisementPage(data);
};
const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};
const getCount = async (data: any) => {
	const res = await advertisementCount(data);
	if (res.code == 200) {
		tags.value[0].data = res.data.totalCount;
		tags.value[1].data = res.data.pendingCount;
		tags.value[2].data = res.data.processingCount;
		tags.value[3].data = res.data.offlineCount;
	} else {
		ElMessage.error(res.msg);
	}
};
const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});
const toUpdate = (row?: any) => {
	router.push(row ? `/advertisement/list/edit/${row.id}` : `/advertisement/list/add`);
};
const delAdvertisement = async (row: any) => {
	ElMessageBox.confirm('确认删除该广告?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await advertisementDelete({ id: row.id });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};
onMounted(() => {
	// getCount();
});
</script>

<style lang="scss" scoped></style>
